package indi.tshoiasc.simstr.gui;

import java.awt.AWTException;
import java.awt.Robot;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.MaterialData;
import org.bukkit.plugin.Plugin;

import indi.tshoiasc.simstr.SimStrengthMain;
import indi.tshoiasc.simstr.config.ConfigHolder;
import indi.tshoiasc.simstr.config.ConfigLoader;
import indi.tshoiasc.simstr.utils.GeneralOperate;
import indi.tshoiasc.simstr.utils.VaultOperate;

@SuppressWarnings("deprecation")
public class Gui implements Listener {
	public static Map<Player, Inventory> gui = new HashMap<Player, Inventory>();
	private static String GUINAME = "强化锻造炉";
	static Map<Player, Long> map = new HashMap<Player, Long>();
	static ItemStack green_glass = new MaterialData(Material.STAINED_GLASS_PANE, Byte.parseByte("5")).toItemStack();
	static ItemStack yellow_glass = new MaterialData(Material.STAINED_GLASS_PANE, Byte.parseByte("4")).toItemStack();
	static ItemStack orange_glass = new MaterialData(Material.STAINED_GLASS_PANE, Byte.parseByte("1")).toItemStack();
	static ItemStack end_portal = new ItemStack(119);
	static ItemStack fire = new ItemStack(51);
	static ItemStack water = new ItemStack(9);
	static ItemStack lava = new ItemStack(10);
	static ItemStack fumotai = new ItemStack(116);
	static ItemStack ironl = new ItemStack(101);
	static ItemStack modi = new ItemStack(120);
	static ItemStack tiezhen = new ItemStack(145);
	static int[] jinduPositon = new int[] { 45, 46, 47, 48, 49, 50, 51, 52, 53 };
	static int volume = 54;
	static Map<Player, Boolean> inStrenghthening = new HashMap<Player, Boolean>();
	public static SimStrengthMain plugin;
	static int[] CostPosition = new int[] { 13, 14, 15, 22, 23, 24 };
	static int[] waterPositon = new int[] { 0, 1, 2, 9, 11, 18, 20, 27, 28, 29, 36, 37, 38 };
	public static Map<Player, Map<Integer, ItemStack>> qhmap = new HashMap<Player, Map<Integer, ItemStack>>();// 0强化装备
	// 1-6强化物品

	public static void initGui() {
		ItemMeta end_portale = end_portal.getItemMeta();
		end_portale.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&6&l") + "开始强化");
		end_portal.setItemMeta(end_portale);
		ItemMeta green_glasse = green_glass.getItemMeta();
		green_glasse.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&2&l") + "进度条");
		green_glass.setItemMeta(green_glasse);
		ItemMeta yellow_glasse = yellow_glass.getItemMeta();
		yellow_glasse.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&e&l") + "进度条");
		yellow_glass.setItemMeta(yellow_glasse);
		ItemMeta watere = water.getItemMeta();
		watere.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&3&l") + "冷水缓冲");
		water.setItemMeta(watere);
		ItemMeta ironle = ironl.getItemMeta();
		ironle.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&7&l") + "反应炉隔板");
		ironl.setItemMeta(ironle);
		ItemMeta orange_glasse = orange_glass.getItemMeta();
		orange_glasse.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&6&l") + "炽热的铁板");
		orange_glass.setItemMeta(orange_glasse);
		ItemMeta lavae = lava.getItemMeta();
		lavae.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&4&l") + "灼热的水");
		lava.setItemMeta(lavae);
		ItemMeta fumotaie = fumotai.getItemMeta();
		fumotaie.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&e&l") + "上等的强化台");
		fumotai.setItemMeta(fumotaie);
		ItemMeta modie = modi.getItemMeta();
		modie.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&6&l") + "幸运石放置台");
		modi.setItemMeta(modie);
		ItemMeta tiezhene = tiezhen.getItemMeta();
		tiezhene.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&3&l") + "保护石放置台");
		tiezhen.setItemMeta(tiezhene);
		ItemMeta firee = fire.getItemMeta();
		firee.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&4&l") + "高温火焰");
		fire.setItemMeta(firee);
	}

	private static void changeButtonTitle(String title) {
		ItemMeta e = end_portal.getItemMeta();
		e.setDisplayName(title);
		end_portal.setItemMeta(e);
	}

	@EventHandler(priority = EventPriority.LOWEST)
	public void InventoryCloseEvent(InventoryCloseEvent evt) {
		if (evt.getPlayer() instanceof Player == false) {
			return;
		}
		final Player p = (Player) evt.getPlayer();
		if (inStrenghthening.containsKey(p) && inStrenghthening.get(p)) {
			if (evt.getInventory().getTitle().equalsIgnoreCase(GUINAME)) {
				new Thread() {
					@Override
					public void run() {
						try {
							Thread.sleep(1);
						} catch (InterruptedException e) {

							e.printStackTrace();
						}
						p.openInventory(gui.get(p));
						p.sendMessage("请等待强化结束");
					}

				}.start();

			}
		}
	}

	@SuppressWarnings("unchecked")
	@EventHandler(priority = EventPriority.HIGH)
	public void InventoryClickEvent(final InventoryClickEvent evt) {

		if (evt.isCancelled()) {
			return;
		}
		if (evt.getWhoClicked() instanceof Player == false) {
			return;
		}
		if (!evt.getInventory().getTitle().equalsIgnoreCase(GUINAME)) {
			return;
		}
		final Player p = (Player) evt.getWhoClicked();
		if (inStrenghthening.containsKey(p) && inStrenghthening.get(p) == true) {
			evt.setCancelled(true);
			return;
		}
		int loc = evt.getRawSlot(); // 获取点击位置
		// (物品栏第一位置54 最后一位置80 手栏 第一位置81 最后位置89)
		final Inventory inv = evt.getInventory();
		if (loc < volume && loc >= 0) {
			switch (loc) {
			case 44: // 强化按钮位置
				evt.setCancelled(true);
				changeButtonTitle(ChatColor.translateAlternateColorCodes('&', "&e&l") + "开始强化");
				inv.setItem(44, end_portal);
				p.updateInventory();
				inStrenghthening.put(p, true);
				Inventory temp = Bukkit.createInventory(p, 54);
				ItemStack equipment = inv.getItem(10);
				if (equipment == null || equipment.getType() == Material.AIR) {
					changeButtonTitle(ChatColor.translateAlternateColorCodes('&', "&4&l") + "请放入强化装备");
					inv.setItem(44, end_portal);
					p.updateInventory();
					inStrenghthening.put(p, false);
					return;
				} else if (!ConfigLoader.list.containsKey(equipment.getTypeId())) {
					changeButtonTitle(ChatColor.translateAlternateColorCodes('&', "&4&l") + "该装备不支持强化");
					inv.setItem(44, end_portal);
					p.updateInventory();
					inStrenghthening.put(p, false);
					return;
				}
				int level = GeneralOperate.getLevel(equipment);
				if (level == 10) {
					p.sendMessage("§6武器已满级，无法继续强化。");
					inStrenghthening.put(p, false);
					return;
				}
				// 判断是否为幸运强化或保护强化
				boolean luck;
				boolean safe;
				ConfigHolder setting = (ConfigHolder) ConfigLoader.list.get(Integer.valueOf(equipment.getTypeId()));

				if (map.get(p) == null) {
					map.put(p, Long.valueOf(System.currentTimeMillis()));
				} else {
					long cooldowna = System.currentTimeMillis();
					long cooldowne = map.get(p).longValue();
					if (cooldowna - cooldowne < ConfigHolder.getCooldown()) {
						p.sendMessage("§b强化冷却中……还需§2"
								+ Math.ceil((ConfigHolder.getCooldown() - (cooldowna - cooldowne)) / 1000.0D) + "§b秒");
						inStrenghthening.put(p, false);
						return;
					}
					map.put(p, Long.valueOf(System.currentTimeMillis()));
				}

				ItemStack luckitem = (ItemStack) setting.getLuck().get("costItem");
				ItemStack safeitem = (ItemStack) setting.getSafe().get("costItem");
				ItemStack luck1 = inv.getItem(8);
				ItemStack safe1 = inv.getItem(26);
				luck = compareItem(luckitem, luck1);
				safe = compareItem(safeitem, safe1);
				if ((luck1 != null && luck1.getType() != Material.AIR) && (luck == false)) {
					p.sendMessage("幸运石放置错误");
					inStrenghthening.put(p, false);
					return;
				}
				if ((safe1 != null && safe1.getType() != Material.AIR) && (safe == false)) {
					p.sendMessage("保护石放置错误");
					inStrenghthening.put(p, false);
					return;
				}
				// 看看钱够不够
				int money = ((Integer) setting.getNormal().get("costMoney")).intValue()
						+ (luck ? ((Integer) setting.getLuck().get("costMoney")).intValue() : 0)
						+ (safe ? ((Integer) setting.getSafe().get("costMoney")).intValue() : 0);
				if (!VaultOperate.has(p.getName(), money)) {
					p.sendMessage("§4您没有足够的金钱,强化所需§2" + money);
					inStrenghthening.put(p, false);
					return;
				} else {
					VaultOperate.take(p.getName(), money);
				}
				// 测试一下消耗物品
				List<ItemStack> list = new ArrayList<ItemStack>();
				list = (List<ItemStack>) setting.getNormal().get("costItem");
				for (int i : CostPosition) {
					ItemStack im = inv.getItem(i);
					if (im == null || im.getType() == Material.AIR) {
						continue;
					}
					temp.addItem(im);
				}
				if (takeItem(temp, list, false)) {
					// 幸运8 保护26
					if (luck) {
						luck1.setAmount(luck1.getAmount() - 1);
					}
					if (safe) {
						safe1.setAmount(safe1.getAmount() - 1);
					}

					inv.setItem(8, luck1);
					inv.setItem(26, safe1);
					// 清空强化物品
					for (int i : CostPosition) {
						inv.setItem(i, null);
					}
					ListIterator<ItemStack> e = temp.iterator();
					List<ItemStack> storage = new ArrayList<ItemStack>();
					for (; e.hasNext();) {
						ItemStack gain = e.next();
						if (gain != null && gain.getType() != Material.AIR) {
							storage.add(gain);
						}

					}

					outer: for (ItemStack a : storage) {
						for (int i : CostPosition) {
							if (inv.getItem(i) == null || inv.getItem(i).getType() == Material.AIR) {
								inv.setItem(i, a);
								continue outer;
							}
						}
					}
					temp.clear();

					new StartStrength(inv, p, equipment, setting, level, luck, safe).start();
					;
				} else {
					changeButtonTitle(ChatColor.translateAlternateColorCodes('&', "&4&l") + "材料不足");
					inv.setItem(44, end_portal);
					p.updateInventory();
					temp.clear();
					inStrenghthening.put(p, false);
				}

				break;
			case 10: // 强化装备位置
				break;
			// -----------
			// 强化物品位置
			case 8: // 幸运石位置
				break;
			case 26: // 保护石位置
				break;
			case 13:

				break;
			case 14:

				break;
			case 15:

				break;
			case 22:

				break;
			case 23:

				break;
			case 24:
				break;
			default:
				evt.setCancelled(true);
				break;
			}

		} else if (loc >= volume)

		{
			if (evt.isShiftClick()) {
				evt.setCancelled(true);
			}
		}

	}

	private static boolean compareItem(ItemStack a1, ItemStack a2) {
		if (a1 == null || a2 == null) {
			return false;
		}
		ItemMeta i1 = a1.getItemMeta();
		ItemMeta i2 = a2.getItemMeta();
		if (i1.hasLore() && i2.hasLore()) {
			if (!i1.getDisplayName().equals(i2.getDisplayName())) {
				return false;
			}
			if (i1.getLore().equals(i2.getLore())) {
				return true;
			} else {
				return false;
			}
		} else {
			if (!i1.getDisplayName().equals(i2.getDisplayName())) {
				return false;
			} else {
				return true;
			}
		}

	}

	public static void OpenGui(Player p) {
		if (gui.containsKey(p)) {
			// 如果有这个gui则打开
			Inventory obtain = gui.get(p);
			p.closeInventory();
			p.openInventory(obtain);
		} else {
			// 如果没有则新建然后再打开
			Inventory creation = Bukkit.createInventory(p, volume, GUINAME);
			ItemStack[][] compose = new ItemStack[][] {
					{ water, water, water, ironl, orange_glass, orange_glass, orange_glass, ironl, null },
					{ water, null, water, ironl, null, null, null, ironl, modi },
					{ water, fumotai, water, ironl, null, null, null, ironl, null },
					{ water, water, water, ironl, orange_glass, orange_glass, orange_glass, ironl, tiezhen },
					{ water, water, water, ironl, fire, fire, fire, ironl, end_portal },
					{ green_glass, green_glass, green_glass, green_glass, green_glass, green_glass, green_glass,
							green_glass, green_glass } };
			for (int i = 0; i < volume; i++) {
				int index1 = i / 9;
				int index2 = i % 9;
				creation.setItem(i, compose[index1][index2]);
			}

			// 创建完毕 放map里
			gui.put(p, creation);
			p.closeInventory();
			p.openInventory(creation);
		}
	}

	public static boolean hasItem(Inventory inv, List<ItemStack> im) {
		boolean flag = true;
		for (int i = 0; i < im.size(); i++) {
			ItemStack it = (ItemStack) im.get(i);
			HashMap<Integer, ? extends ItemStack> itemlist = inv.all(((ItemStack) im.get(i)).getType());
			Collection<? extends ItemStack> value = itemlist.values();
			int result = 0;
			for (ItemStack items : value) {
				if ((items.getItemMeta().equals(it.getItemMeta())) || ((!items.hasItemMeta()) && (!it.hasItemMeta()))) {
					result += items.getAmount();
				}
			}
			if (result < it.getAmount()) {
				flag = false;
				break;
			}
		}
		return flag;
	}

	public static boolean takeItem(Inventory inv, List<ItemStack> im, boolean has) {
		if ((!has) && (!hasItem(inv, im))) {
			return false;
		}
		for (ItemStack it : im) {
			inv.removeItem(new ItemStack[] { it });
		}
		return true;
	}

	public static void getPlugin(SimStrengthMain e) {
		plugin = e;
	}

}

class StartStrength extends Thread {
	Player p;
	Inventory inv;
	ItemStack equipment;
	ConfigHolder setting;
	int level;
	boolean luck, safe;

	public StartStrength(Inventory inv, Player p, ItemStack equipment, ConfigHolder setting, int level, boolean luck,
			boolean safe) {
		this.p = p;
		this.inv = inv;
		this.equipment = equipment;
		this.setting = setting;
		this.level = level;
		this.luck = luck;
		this.safe = safe;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void run() {
		for (int i : Gui.waterPositon) {
			inv.setItem(i, Gui.lava);
		}
		// 开始强化
		// 进度条开始

		for (int i = 0; i < Gui.jinduPositon.length; i++) {

			Robot r;
			try {
				r = new Robot();
				r.delay(500);
			} catch (AWTException f) {
				f.printStackTrace();
			}

			inv.setItem(Gui.jinduPositon[i], Gui.yellow_glass);
			p.updateInventory();
		}
		// 强化
		int addRandom = 0;
		if (luck) {
			addRandom = ((Integer) setting.getLuck().get("addRandom")).intValue();
		}

		Object aa = setting.getNormal().get("random");
		List<Integer> temp = (List<Integer>) aa;
		Integer ccc = temp.get(level);

		if (GeneralOperate.random(ccc + addRandom)) {
			p.sendMessage("§6强化成功,当前强化等级为§5§l" + (level + 1) + "§6级");
			p.getWorld().playEffect(p.getLocation(), ConfigHolder.successEffect, 5);
			String namename;
			if (equipment.getItemMeta().getDisplayName() == null) {
				namename = setting.getName();
			} else {
				namename = p.getItemInHand().getItemMeta().getDisplayName();
			}
			if (level + 1 >= ConfigHolder.Broadcast_level) {
				String broadcast = ConfigHolder.getBroadcast_content().replace("%playername%", p.getName())
						.replace("%level%", "" + (level + 1)).replace("%item%", namename);
				Bukkit.broadcastMessage(broadcast);
			}
			GeneralOperate.setLevel(equipment, level + 1);

		} else {
			if ((level >= 7) && (!safe)) {
				p.setItemInHand(new ItemStack(Material.AIR));
				p.sendMessage("§4强化失败,物品已损坏");
				p.getWorld().playEffect(p.getLocation(), ConfigHolder.failEffect, 5);
				inv.setItem(10, null);
				p.updateInventory();
			} else {
				if (safe) {
					p.sendMessage("§4强化失败,保护强化不降低等级");
					p.getWorld().playEffect(p.getLocation(), ConfigHolder.failEffect, 5);

				} else {
					if (level == 0) {
						p.sendMessage("§4强化失败");
						p.getWorld().playEffect(p.getLocation(), ConfigHolder.failEffect, 5);
						inv.setItem(10, equipment);
						p.updateInventory();
					} else {
						p.sendMessage("§4强化失败,强化等级下降为§5" + (level - 1) + "§4级");
						GeneralOperate.setLevel(equipment, level - 1);
						p.getWorld().playEffect(p.getLocation(), ConfigHolder.failEffect, 5);
						inv.setItem(10, equipment);
						p.updateInventory();
					}

				}
			}

		}

		// 进度条归位
		for (int i : Gui.jinduPositon) {
			inv.setItem(i, Gui.green_glass);
		}
		for (int i : Gui.waterPositon) {
			inv.setItem(i, Gui.water);
		}
		p.updateInventory();
		Gui.inStrenghthening.put(p, false);
		Gui.map.put(p, Long.valueOf(System.currentTimeMillis()));
	}
}
